<?php

namespace frontend\controllers;

use bc\controller\FrontController;
use bc\model\MothersdayModel;
use yii\web\Session;

class MothersController extends FrontController
{
	
	public function actionIndex()
	{
		
		$this->setOAuth();
		
		$session = new Session();
		$user = $session->get('user');
		
		if(!$user)
			$this->redirect('/');
		
		$mothersdayModel = new MothersdayModel();
		$row = $mothersdayModel->getRow(['openid' => $user['openid']]);
		if($row)
			$this->redirect('/mothers/save');
		
		
		$view = [];
		return $this->render('index', $view);
	}
	
	
	public function actionImage()
	{
		$img = $this->post('imgData');
		$img = str_replace('data:image/jpeg;base64,', '', $img);
		$img = str_replace(' ', '+', $img);
		$data = base64_decode($img);
		$imageid = uniqid();
		$path = UPLOAD_PATH . 'mother/';
		
		if(!file_exists($path)) {
			$this->createDir($path);
		}
		$file = $path.$imageid.'.jpg';
		
		$success = file_put_contents($file, $data);
		
		$save_path = 'mother/'.$imageid.'.jpg';
		
		$result['imagePath'] = $save_path;
		
		if($success > 0)
		{
			$result['result'] = 1;
		}
		else 
		{
			$result['result'] = 0;
			$result['msg'] = '上传失败';
		}
		
		
		echo json_encode($result);
		exit;
		
	}
	
	public function actionSave()
	{
		$session = new Session();
		$user = $session->get('user');
		if(!$user)
			$this->redirect('/');
		
		$mothersdayModel = new MothersdayModel();
		
		$row = $mothersdayModel->getRow(['openid' => $user['openid']]);
		if(!$row)
		{
			$data['openid'] = $user['openid'];
			$data['image'] = $this->post('image_path');
			$data['name'] = $this->post('user');
			$data['tel'] = $this->post('phone');
			$data['address'] = $this->post('address');
			$data['zipcode'] = $this->post('postcode');
			$data['description'] = $this->post('description');
			$data['create_time'] = time();
			$mothersdayModel->add($data);
		}
		
		return $this->render('save');
	}

	protected function createDir($path) 
	{
		if (! file_exists ( $path )) {
			$this->createDir ( dirname ( $path ) );
			mkdir ( $path, 0777 );
		}
	}
	
}

